package joey.project1.view

import groovy.swing.factory.ImageIconFactory

import java.awt.Image

class SizeImageIconFactory extends ImageIconFactory {
	public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) {
		if (value == null) {
			if (attributes.containsKey("image")) {
				value = attributes.remove("image")
				if (!(value instanceof Image)) {
					throw new RuntimeException("In $name image: attributes must be of type java.awt.Image")
				}
			} else if (attributes.containsKey("url")) {
				value = attributes.remove("url")
				if (!(value instanceof URL)) {
					throw new RuntimeException("In $name url: attributes must be of type java.net.URL")
				}
			} else if (attributes.containsKey("file")) {
				value = attributes.remove("file")
				if (value instanceof GString) value = value as String
				if (value instanceof File) {
					value = value.toURL()
				} else if (!(value instanceof String)) {
					throw new RuntimeException("In $name file: attributes must be of type java.io.File or a string")
				}
			}
		} else if (value instanceof GString) {
			value = value as String
		}

		// not else if so we can adjust for the case of file string where the file does not exist
		def resource = null
		if ((value == null) && (attributes.containsKey("resource"))) {
			resource = attributes.remove('resource')
		} else if ((value instanceof String) && !(new File(value).exists())) {
			resource = value
		}
		if (resource != null) {
			def klass = builder.context.owner
			def origValue = value
			if (attributes.containsKey("class")) {
				klass = attributes.remove("class")
			}
			if (klass == null) {
				klass = ImageIconFactory
			} else if (!(klass instanceof Class)) {
				klass = klass.class
			}
			// for now try URL approach.
			// we may need to extract the byte[] for some packaging cases
			value = klass.getResource(resource)
			if (value == null) {
				throw new RuntimeException("In $name the value argument '$origValue' does not refer to a file or a class resource")
			}
		}

		if (value == null) {
			throw new RuntimeException("$name has neither a value argument or one of image:, url:, file:, or resource:")
		}
		SizeImageIcon icon
		// exploit multi-dispatch in constructor calls
		if (attributes.containsKey("description")) {
			icon = new SizeImageIcon(value, attributes.remove("description"))
		} else {
			icon = new SizeImageIcon(value)
		}
		if(attributes.containsKey('width') && attributes.containsKey('height')){
			icon.width = attributes.remove('width')
			icon.height = attributes.remove('height')
		}
		return icon
	}
}
